﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CommonMvc.Common
{

    public interface IWorkContext
    {
        bool IsLogin { get; }
        IUser CurrentUser { get; }

        void Refresh(IUser user);
        ICookieManager GetCookieManager();
    }

    public class WebWorkContext : IWorkContext
    {
        UserType _userType = UserType.App;
        ICookieManager _cookieManager;
        IAppContext _appContext;
        String _cookieValue;
        protected ILogger _logger = LogManager.GetLogger("file");
        public WebWorkContext(ICookieManager cookieManager,IAppContext appContext) {
            _cookieManager = cookieManager;
            _appContext = appContext;
            ParseWork();
        }
        /// <summary>
        /// 通过appcontext  获取对应的cookie key 再获取当时写入的cookie 解析用户类型
        /// </summary>
        private void ParseWork()
        {            
            WebAppContext webAppContext = _appContext as WebAppContext;
            App app = webAppContext.CurrentApp as App;
            if (app.Platform == PlatformType.Sys)
            {
                _userType = UserType.Sys;
                _cookieValue = _cookieManager.GetCookieValue("Sys");
                
            }
            else if (app.Platform == PlatformType.WeiXin)
            {
                _userType = UserType.WeiXin;
                _cookieValue = _cookieManager.GetCookieValue("WeiXin");
            }
            else if (app.Platform == PlatformType.App) {
                _userType = UserType.App;
                _cookieValue = _cookieManager.GetCookieValue("App");
            }
            try
            {
                _logger.Info("用户类型是" + _userType.ToString());
                _user = JsonConvert.DeserializeObject<User>(_cookieValue);

            }
            catch (Exception e) {
                Debug.Write(e);
                _user = new User{
                    UserId = 0,
                    UserType = UserType.App,
                    UnionId = "",
                    IsLogin = false
                };         
            } 
        }

        User _user = null;
        public bool IsLogin {
            get {
                if (_user == null) {
                    return false;
                }
                return _user.IsLogin;
            }
        }

        public IUser CurrentUser {
            get {
                return _user;
            }
        }

        public void Refresh(IUser user)
        {
            if (user == null)
            {
                return;
            }
            else {
                _user = (User)user;
            }
          
        }
        public ICookieManager GetCookieManager() {
            return _cookieManager;
        }
    }

    public enum PlatformType
    {
        Sys,//系统管理平台
        WeiXin,//微信浏览器平台
        App,//app平台
    }

    public interface IApp
    {
        int AppId { get; set; }
    }

    public class App : IApp
    {
        #region IApp 成员

        private int _AppId = 0;
        /// <summary>
        /// 应用id, app默认为0，商家默认为商家id
        /// </summary>
        public int AppId
        {
            get
            {
                return _AppId;
            }
            set
            {
                _AppId = value;
            }
        }

        #endregion

        /// <summary>
        /// 平台类型
        /// </summary>
        public PlatformType Platform { get; set; }

        public string AppName { get; set; }

        /// <summary>
        /// 是否是后台管理
        /// </summary>
        public bool IsAdmin { get; set; }

        public int MainAppId { get { return 0; } }
    }

    public interface IAppContext
    {
        IApp CurrentApp { get; }

        void Refresh(IApp app);
        
    }
    //通过请求的uri 来判断用户的平台类型
    public class WebAppContext : IAppContext
    {
       
        static string SysMRegex = @"/sysmanager(/|$)";//判断域名是否是系统管理后台
        App _app = null;
 
        private readonly HttpContext _httpContext;
        public WebAppContext(IHttpContextAccessor httpContextAccessor)
        {
            
            this._httpContext = httpContextAccessor.HttpContext;

            _app = ParseWebHost();

        }

        private App ParseWebHost()
        {
            App app = new App()
            {
                Platform = PlatformType.WeiXin,
                AppId = 0
            };
            string segment = _httpContext.Request.Path;         
            //判断是否是管理页面
            if (Regex.IsMatch(segment, SysMRegex, RegexOptions.IgnoreCase))
            {
                app.IsAdmin = true;
                app.Platform = PlatformType.Sys;
            }
            return app;
        }

        public virtual IApp CurrentApp
        {
            get { return _app; }
        }

        public void Refresh(IApp app)
        {
            if (app == null)
            {
                this._app = ParseWebHost();
            }
            else
            {
                _app = (App)app;
            }
        }

       
    }



}
